use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use clap::{arg, command, ArgAction, ArgMatches};

fn main() {
    let matches = get_match();

    println!("{}", matches.get_flag("all"));
    if let Some(suffix) = matches.get_one::<String>("suffix") {
        println!("suffix: {suffix}")
    }

    let files = matches.get_many::<String>("FILEoDIR")
        .expect("don't have file args");

    for file_name in files {
        let pth = Path::new(file_name);
        // println!("{:?}", pth);
        // println!("{} {}", pth.is_file(), pth.is_dir());
        if pth.is_file() {
            println!("{:?}", cnt_line(
                &File::open(pth).expect("can't open")
            ));
        } else if pth.is_dir() {}
    }
}

fn cnt_line(f: &File) -> (u32, u32, u32) {
    let mut nblank = 0;
    let mut blank = 0;
    let mut buf = String::new();
    let reader = BufReader::new(f);

    for l in reader.lines() {
        if let Ok(line) = l {
            match line.is_empty() {
                true => blank += 1,
                false => nblank += 1
            }
            buf = line;
        }
    }

    if buf.is_empty() { blank += 1; };

    (nblank, blank, nblank + blank)
}

fn get_match() -> ArgMatches {
    command!() // requires `cargo` feature
        .arg(
            arg!([FILEoDIR] "FILE or DIR to operate on")
                .action(ArgAction::Append)
        )
        .arg(arg!( -A --all "print the total line number only" )
            .action(ArgAction::SetTrue))
        .arg(arg!( -b --ignoreb "ignore the Blank line when counting" )
            .action(ArgAction::SetTrue))
        .arg(arg!( -r --recursive "count directory Recursively" )
            .action(ArgAction::SetTrue))
        .arg(arg!( -s --suffix <"FILE-SUFFIX"> "only count the file with specified Suffix" ))
        .get_matches()
}
